from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .models import KeyPart
from .serializers import KeyPartSerializer


class KeyPartViewSet(viewsets.ModelViewSet):
    """关键备件视图集"""
    
    queryset = KeyPart.objects.all()
    serializer_class = KeyPartSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['item_name', 'model', 'user_name']
    search_fields = ['item_name', 'model', 'purpose', 'user_name', 'remarks']
    ordering_fields = ['created_at', 'updated_at', 'stock_in_time', 'used_time']
    ordering = ['-created_at']
    
    @action(detail=False, methods=['get'])
    def by_item(self, request):
        """按物品名称分组获取备件信息"""
        item_name = request.query_params.get('name')
        if not item_name:
            return Response({'error': '请提供物品名称参数'}, status=400)
        
        parts = self.queryset.filter(item_name__icontains=item_name)
        serializer = self.get_serializer(parts, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取库存统计信息"""
        total_items = self.queryset.count()
        total_inventory = sum(part.inventory_quantity for part in self.queryset.all())
        total_used = sum(part.used_quantity for part in self.queryset.all())
        
        return Response({
            'total_items': total_items,
            'total_inventory': total_inventory,
            'total_used': total_used,
            'usage_rate': round(total_used / (total_inventory + total_used) * 100, 2) if (total_inventory + total_used) > 0 else 0
        })
    
    @action(detail=False, methods=['post'])
    def bulk_create(self, request):
        """批量创建关键备件记录"""
        data = request.data
        if not isinstance(data, list):
            return Response({'error': '数据必须是数组格式'}, status=400)
        
        serializer = self.get_serializer(data=data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
